﻿using SqlSugar;
using System;
using System.Configuration;
using System.Linq;

namespace 完工订单定时任务
{
    public static class SQLSERVERSqlSugarHelp
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        public static SqlSugarScope scope = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString,//连接符字串
            DbType = DbType.SqlServer,//数据库类型
            IsAutoCloseConnection = true //不设成true要手动close
        },
           db =>
           {
               db.Aop.OnLogExecuting = (sql, pars) =>
        {
            Logger.Info(sql);//输出sql
            Logger.Info(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));//参数
        };
               db.Aop.OnError = (exp) =>//SQL报错
           {
               Logger.Error(exp.Sql);
           };
               db.Aop.OnLogExecuted = (sql, p) =>
               {
                   //执行时间超过1秒
                   if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                   {
                       //代码CS文件名
                       var fileName = db.Ado.SqlStackTrace.FirstFileName;
                       //代码行数
                       var fileLine = db.Ado.SqlStackTrace.FirstLine;
                       //方法名
                       var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                       Logger.Warn("执行超过1s的sql【" + sql + "】代码CS文件名【" + fileName + "】代码行数【" + fileLine + "】");
                   }
               };
           }

           );
    }
}
